<template>
   <view class="home">
      <!--顶部导航栏-->
      <NavBar :top="safeAreaInsets?.top"></NavBar>
      <!--轮播图-->
      <Carousel :list="bannerList"></Carousel>
      <!--分类面板-->
      <CategoryPanel :list="navList"></CategoryPanel>
      <!-- 热门推荐-->
      <HotPanel :list="hotList"></HotPanel>
      <!--新鲜好物-->
      <GuessCard :list="newList" title="新鲜好物"></GuessCard>
      <!--猜你喜欢-->
      <GuessCard :list="guessList" :loading-text="loadingText" title="猜你喜欢"></GuessCard>
   </view>
</template>

<script setup lang="ts">
import { computed, shallowRef } from "vue";
import { storeToRefs } from "pinia";
import { onLoad, onPullDownRefresh, onReachBottom } from "@dcloudio/uni-app";
import useHomeStore from "@/pinia/modules/homeStore";
import NavBar from "./components/NavBar/NavBar.vue";
import CategoryPanel from "./components/CategoryPanel/CategoryPanel.vue";
import HotPanel from "./components/HotPanel/HotPanel.vue";
import type { PageDTO } from "@/types/homeType";

const homeStore = useHomeStore();
const { safeAreaInsets } = uni.getSystemInfoSync();
const { bannerList, navList, hotList, guessList, total, newList } = storeToRefs(homeStore);
const page = shallowRef<PageDTO>({ page: 1, pageSize: 10 });
const loadingText = computed(() => guessList.value.length >= total.value ? "数据加载完毕!" : "数据正在加载中···");
// 获取首页轮播图
const fetchBannerList = async () => {
   try {
      await homeStore.fetchBannerList(1);
   } catch (error: any) {
      await uni.showToast({ title: error.message, icon: "error" });
   }
};
// 获取分类导航
const fetchNavList = async () => {
   try {
      await homeStore.fetchNavList();
   } catch (error: any) {
      await uni.showToast({ title: error.message, icon: "error" });
   }
};
// 获取热门推荐
const fetchHotList = async () => {
   try {
      await homeStore.fetchHotList();
   } catch (error: any) {
      await uni.showToast({ title: error.message, icon: "error" });
   }
};
// 获取猜你喜欢
const fetchGuessList = async () => {
   try {
      await homeStore.fetchGuessList(page.value);
   } catch (error: any) {
      await uni.showToast({ title: error.message, icon: "error" });
   }
};
// 获取新鲜好物
const fetchNewList = async () => {
   try {
      await homeStore.fetchNewList(6);
   } catch (error: any) {
      await uni.showToast({ title: error.message, icon: "error" });
   }
};
onLoad(async () => {
   await Promise.all([fetchBannerList(), fetchNavList(), fetchHotList(), fetchGuessList(), fetchNewList()]);
});
onPullDownRefresh(async () => {
   uni.stopPullDownRefresh;
   page.value.page = 1;
   guessList.value = [];
   fetchGuessList();

});
onReachBottom(() => {
   fetchGuessList();
});
</script>

<style scoped lang="scss">
page {
   background-color: #f7f7f7;
   height: 100%;
}
/* #ifdef MP-WEIXIN */
.home {
   background-color: #f7f7f7;
}
/* #endif */
</style>
